<template>
  <div class="w-full" :style="{ height: `${screenHeight *0.99}px` }">
    <Grid>
      <template #toolbarButtons>
        <el-button type="primary" @click="addWorkshopScheduling">添加车间排产</el-button>
      </template>
      <template #action="{ row }">
        <template v-if="hasEditStatus(row)">
          <Button type="link" @click="saveRowEvent(row)">保存</Button>
          <Button type="link" @click="cancelRowEvent(row)">取消</Button>
        </template>
        <template v-else>
          <el-button v-if="row.state == 0" link type="primary" @click="updateWorkshopSchedulingState(row)">生效</el-button>
          <el-button link type="primary">查看</el-button>
          <el-button link type="primary" @click="editRowEvent(row)">编辑</el-button>
          <!-- <el-button text type="primary" @click="updateWorkshopScheduling(row)">编辑</el-button> -->
          <el-button link type="primary" @click="delRowEvent(row)">删除</el-button>
        </template>
      </template>
    </Grid>
  </div>
</template>

<script lang="ts" setup>
//@ts-ignore
import type { VbenFormProps } from "#/adapter/form";
import { useRouter,useRoute } from "vue-router";
import type { VxeGridProps, VxeGridListeners } from "#/adapter/vxe-table";
import { ElMessage, ElMessageBox, ElInput,ElForm,ElFormItem, ElDialog,ElButton,ElLoading,ElTag,ElDatePicker,ElNotification,formatter} from "element-plus";
import { Button, Upload, RadioButton, RadioGroup } from "ant-design-vue";
import { useVbenVxeGrid } from "#/adapter/vxe-table";
import { confirm } from '@vben/common-ui';
import { nextTick, ref, onUnmounted, onMounted,reactive, unref, watch } from "vue";
import { dealVxeGridFilterParameter } from "#/utils/tools";
import { reqWorkshopScheduleLing,reqSaveOrUpdateWorkshopPlan } from "#/api/productionPlan";
const router = useRouter();
//@ts-ignore
import { useOtherStore } from "#/store/index.ts";
const otherStore = useOtherStore();


const screenHeight = ref<number>(window.innerHeight);

const handleResize = () => {
  screenHeight.value = window.innerHeight;
}
onMounted(() => {
  window.addEventListener("resize", handleResize);
});
onUnmounted(() => {
   window.removeEventListener("resize", handleResize);
});

const filterParams = ref(null);
const count = ref(0);

let gridFilterParameter = null;

const gridOptions: VxeGridProps = ref({
  columns: [
    { title: "#", type: "seq", width: 50 },
    {
      field:"schedulingDate",
      title:"排产日期",
      width:"150",
      filters: [""],
      filterRender: { name: "customizeFilter",type:"date" }
    },
    { 
      field:"workOrderNumber",
      title:"生产工单号",
      width:"150",
      filters: [""],
      filterRender: { name: "customizeFilter",type:"input" }
    },
    { 
      field:"instructionNumber",
      title:"制令号",
      width:"150",
      filters: [""],
      filterRender: { name: "customizeFilter",type:"input" }
    },
    { 
      field:"state",
      title:"状态",
      width:"100",
      formatter:({ cellValue,row,column }) => { return dealStatus(cellValue) },
    },
    {
      field:"materialName",
      title:"物料名称",
      width:"120",
      filters: [""],
      filterRender: { name: "customizeFilter",type:"input" }
    },
    { 
      field:"materialCode",
      title:"物料编码",
      width:"120",
      filters: [""],
      filterRender: { name: "customizeFilter",type:"input" }
    },
    { field:"schedulingQuantity",title:"排产数量",width:"100" },
    { field:"gripName",title:"车间名称",width:"120" },
    { field:"lineName",title:"产线名称",width:"120" },
    { field:"craftName",title:"工艺",width:"120" },
    { 
      field:"procedureList",
      title:"工序",
      width:"150",
      formatter:({ column,row,cellValue }) => {
        return dealProcessNames(cellValue);
      }
    },
    { field:"layoutMeters",title:"拼板米数",width:"120" },
    { field:"layoutStripCount",title:"拼板条数",width:"120" },
    { 
      field:"remark",
      title:"备注",
      width:"120",
      editRender:{ name:"ElInput" }
    },
    { field:"createdDate",title:"创建日期",width:"150" },
    {
      fixed: "right",
      slots: { default: "action" },
      title: "操作",
      width: 210
    }
  ],
  toolbarConfig: {
    search: false,
    custom: true,
    refresh: true,
    zoom: true,
    slots: {
      buttons: 'toolbarButtons'
    }
  },
  editConfig: {
    trigger: 'click',
    mode: 'cell',
    showStatus: true,
    autoClear: false
  },
  filterConfig: {
    remote: true
  },
  rowConfig: {
    isCurrent: true,
    isHover: true
  },
  keepSource: true,
  pagerConfig: {
    enabled: true,
    pageSize: 20,
    pageSizes: [10, 20, 30, 50, 100]
  },
  height: "auto",
  autoResize:true,
  proxyConfig: {
    autoLoad: true,
    ajax: {
      query: async ({ page }, formValues) => await vxeTableIQueryEvent({page, formValues})
    }
  }
});

const gridEvents: VxeGridListeners = {
  filterChange({ filterList }) {
    gridOptions.loading = true;
    gridFilterParameter = dealVxeGridFilterParameter(filterList);
    gridApi.query();
  }
};

const [Grid, gridApi] = useVbenVxeGrid({formOptions:null,gridOptions:gridOptions,gridEvents:gridEvents});

const vxeTableIQueryEvent = async (option) => {
  try {
    const { page,formValues } = option;
    const params = {
      page: page.currentPage,
      size: page.pageSize
    };
    if(gridFilterParameter) Object.assign(params,gridFilterParameter);
    const response = await reqWorkshopScheduleLing(params);
    return {
      total: response.data.totalElements,
      items: response.data.content
    };
  } catch (error) {
    ElNotification({title:'请求失败',message:'获取计划排产明细列表失败',type:'error'});
    return { total: 0, items: [] };
  }
};


const hasEditStatus = (row: any) => {
  const grid = gridApi.grid;
  if (grid) {
    return grid.isEditByRow(row);
  }
}
const cancelRowEvent = (row:any) => {
  const grid = gridApi.grid;
  if (grid) {
    grid.clearEdit().then(() => {
      grid.revertData(row);
    })
  }
}
const saveRowEvent = (row:any) => {
  confirm({content: '确定保存当前行数据吗?',icon: 'success'}).then(async() => {
    const params = { id:row.id,remark:row.remark }
    await saveOrUpdateWorkshopPlan([params]);
    gridApi.query();
  });
}
const editRowEvent = (row:any) => {
  const grid = gridApi.grid;
  if (grid) {
    grid.setEditRow(row);
  }
}



const addWorkshopScheduling = () => {
  router.push({ name: "WorkShopScheduleAdd" });
}
const updateWorkshopScheduling = (row:any) => {
  otherStore.setTempStore(row);
  router.push({path: "/productionPlan/workShopScheduleEdit/" + row.id});
}
const updateWorkshopSchedulingState = (row:any) => {
  confirm({content: `确定将工单:${row.workOrderNumber}置为生效吗?`,icon: 'success'}).then(async() => {
    const params = { id:row.id,state:1 };
    await saveOrUpdateWorkshopPlan([params]);
    gridApi.grid.query();
  });
}
const delRowEvent = () => {}

const saveOrUpdateWorkshopPlan = (list:any) => {
  return new Promise((resolve, reject) => {
    reqSaveOrUpdateWorkshopPlan(list).then(response => {
      if(response.code == 200){
        ElNotification({title:'提示',message:'保存成功',type:'success'});
      }
      resolve(response);
    }).catch(error => {
      ElNotification({title:'提示',message:'保存失败' + error.message,type:'error'});
      reject(error);
    })
  });
}

const dealStatus = (status:number|string = 0) => {
  status = Number(status);
  let desc = "";
  switch (status) {
    case 0:
      desc = "创建";
      break;
    case 1:
      desc = "生效";
      break;
    case 2:
      desc = "完成";
      break;
    case 3:
      desc = "关闭";
      break;
    case 4:
      desc = "取消";
      break;
    default:
      desc = "未知";
  }
  return desc;
}
const dealProcessNames = (processList = []) => {
  const sortList = processList.sort((a, b) => a.sequence - b.sequence);
  return sortList.map(val => val.procedureName).join("->");
}
</script>
